package com.gengzp.mq.client.core.impl;

import com.gengzp.mq.client.core.MqEnvConfigReader;
import com.gengzp.mq.client.core.MqServerRequestFunc;
import com.gengzp.mq.common.model.base.MqResult;
import com.gengzp.mq.common.model.resp.GengzpMqMessageExt;
import com.gengzp.mq.common.utils.GengzpMqIpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * @ClassName ServerRequestFuncImpl
 * @Description 服务端请求方法实现类
 * @Author gengzp
 * @Date 2025/6/9 23:38
 */
@Component
public class MqServerRequestFuncImpl implements MqServerRequestFunc {

    @Autowired
    private MqEnvConfigReader mqEnvConfigReader;

    private final RestTemplate restTemplate = initRestTemplate();

    @Override
    public GengzpMqMessageExt LongPollingReceiverMessage(String topic, String consumerGroup) {
        // 构建form-data参数
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("topic", topic);
        formData.add("consumerServiceIp", GengzpMqIpUtils.getPublicIp() + ":" + mqEnvConfigReader.getCurrentPort());
        formData.add("consumerServiceName", mqEnvConfigReader.getCurrentServiceName());
        formData.add("consumerGroup", consumerGroup);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        // 发送POST请求
        ResponseEntity<MqResult<GengzpMqMessageExt>> response = restTemplate.exchange(
                mqEnvConfigReader.getMqAddress() + "/gengzp/mq/receive",
                HttpMethod.POST,
                requestEntity,
                new ParameterizedTypeReference<>() {
                }
        );
        if (Objects.isNull(response.getBody())) {
            return null;
        }

        return response.getBody().getData();
    }

    @Override
    public void confirmMessage(Long messageId) {
        // 构建form-data参数
        MultiValueMap<String, Long> formData = new LinkedMultiValueMap<>();
        formData.add("messageId", messageId);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, Long>> requestEntity = new HttpEntity<>(formData, headers);

        // 发送POST请求
        restTemplate.exchange(
                mqEnvConfigReader.getMqAddress() + "/gengzp/mq/confirm",
                HttpMethod.POST,
                requestEntity,
                new ParameterizedTypeReference<>() {
                }
        );
    }

    @Override
    public Long sendMessage(String topic, String messageContent) {
        // 构建form-data参数
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("topic", topic);
        formData.add("messageContent", messageContent);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        // 发送POST请求
        ResponseEntity<MqResult<Long>> response = restTemplate.exchange(
                mqEnvConfigReader.getMqAddress() + "/gengzp/mq/send",
                HttpMethod.POST,
                requestEntity,
                new ParameterizedTypeReference<>() {
                }
        );
        if (Objects.isNull(response.getBody())) {
            return null;
        }

        return response.getBody().getData();
    }

    private RestTemplate initRestTemplate() {
        // 创建基于Apache HttpClient的请求工厂
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        // 配置连接超时时间（毫秒）
        requestFactory.setConnectTimeout(35000);
        // 配置连接请求超时时间（毫秒）
        requestFactory.setConnectionRequestTimeout(35000);

        return new RestTemplate(requestFactory);
    }

}
